﻿using System;
using System.Collections.Generic;
using System.Windows;
using Microsoft.Phone.Controls;
using CarsRegistrationMobile.Managers;
using CarsRegistrationMobile.Models.JSON;

namespace CarsRegistrationMobile.Views
{
    public partial class LogIn : PhoneApplicationPage
    {
        #region Satate

        private string registrationPath;
        private string currentPath;

        #endregion Satate

        private StorageManager StorageManager
        {
            get
            {
                return ((App)Application.Current).StorageManager;
            }
        }

        private NetworkManager NetworkManager
        {
            get
            {
                return ((App)Application.Current).NetworkManager;
            }
        }

        public LogIn()
        {
            InitializeComponent();

            this.registrationPath = "/Views/Registration.xaml";
            this.currentPath = "/Views/LogIn.xaml";
        }

        private void ButtonLogin_Click(object sender, RoutedEventArgs e)
        {
            string passHash = this.StorageManager.MD5Encode(this.PasswordBoxPassword.Password);
            this.NetworkManager.BeginLogin(this.TextBoxLogin.Text,
                                      passHash,
                                      this.LoginCallback);
        }

        public void LoginCallback(JsonResultBase jsonResult, string login, string passHash)
        {
            Dispatcher.BeginInvoke(() =>
            {
                if (NavigationService.CurrentSource.OriginalString != this.currentPath)
                {
                    return;
                }
            });

            if (jsonResult == null || string.IsNullOrWhiteSpace(jsonResult.Result))
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Произошла ошибка");
                });
                return;
            }
            if (jsonResult.ResultCode != 0)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show(jsonResult.Result);
                });
                return;
            }
            this.StorageManager.SaveSettings(new KeyValuePair<string, object>("Login", login));
            this.StorageManager.SaveSettings(new KeyValuePair<string, object>("PassHash", passHash));

            Dispatcher.BeginInvoke(() =>
            {
                Uri uri = new Uri("/Views/Menu.xaml", UriKind.Relative);
                NavigationService.Navigate(uri);
            });
        }

        private void ButtonRegistration_Click(object sender, RoutedEventArgs e)
        {
            Uri uri = new Uri(this.registrationPath, UriKind.Relative);
            NavigationService.Navigate(uri);
        }
    }
}